package com.ikdong.toodle.dao;

import java.util.ArrayList;
import java.util.List;

import com.ikdong.toodle.activity.TaskListActivity;
import com.ikdong.toodle.model.Task;
import com.ikdong.toodle.util.Constant;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;

public class TaskDAO {
	private DataBaseHelper db;
	
	public TaskDAO(Context context){
		db = new DataBaseHelper(context);
	}
	
	public boolean add(Task task,String userid,long opStatus){
		long rlt = -1;
		try{
			db.openDataBase();
			ContentValues values = new ContentValues();
			values.put("userid", userid);
			values.put("_id", task.getId());
			values.put("title", task.getTitle());
			values.put("op_status", opStatus);
			if(task.getTag()!=null)
				values.put("tag",task.getTag());
			if(task.getFolder()!=null)
				values.put("folder",task.getFolder());
			if(task.getContext()!=null)
				values.put("context",task.getContext());
			if(task.getGoal()!=null)
				values.put("goal",task.getGoal());
			if(task.getLocation()!=null)
				values.put("location",task.getLocation());
			if(task.getParent()!=null)
				values.put("parent",task.getParent());
			if(task.getChildren()!=null)
				values.put("children",task.getChildren());
			if(task.getOrder()!=null)
				values.put("ord",task.getOrder());
			if(task.getDuedate()!=null)
				values.put("duedate",task.getDuedate());
			if(task.getDuedatemod()!=null)
				values.put("duedatemod",task.getDuedatemod());
			if(task.getStartdate()!=null)
				values.put("startdate",task.getStartdate());
			if(task.getDuetime()!=null)
				values.put("duetime",task.getDuetime());
			if(task.getStarttime()!=null)
				values.put("starttime",task.getStarttime());
			if(task.getRemind()!=null)
				values.put("remind",task.getRemind());
			if(task.getRepeat()!=null)
				values.put("repeat",task.getRepeat());
			if(task.getRepeatfrom()!=null)
				values.put("repeatfrom",task.getRepeatfrom());
			if(task.getStatus()!=null)
				values.put("status",task.getStatus());
			if(task.getLength()!=null)
				values.put("length",task.getLength());
			if(task.getPriority()!=null)
				values.put("priority",task.getPriority());
			if(task.getStar()!=null)
				values.put("star",task.getStar());
			if(task.getModified()!=null)
				values.put("modified",task.getModified());
			if(task.getCompleted()!=null)
				values.put("completed",task.getCompleted());
			if(task.getAdded()!=null)
				values.put("added",task.getAdded());
			if(task.getTimer()!=null)
				values.put("timer",task.getTimer());
			if(task.getTimeron()!=null)
				values.put("timeron",task.getTimeron());
			if(task.getNote()!=null)
				values.put("note",task.getNote());
			if(task.getMeta()!=null)
				values.put("meta",task.getMeta());
			rlt = db.getWritableDatabase().insert("Task", null, values);	
		}catch(Exception e){
			Log.e(Constant.TAG,"TaskDAO.add() error", e);
		}finally{
			if(db!=null) db.close();
		}
		return rlt>-1;
	}
	
	public boolean update(Task task, long opStatus){
		long rlt = 0;
		try{
			db.openDataBase();
			String where = "_id="+task.getId();
			ContentValues values = new ContentValues();
			values.put("op_status", opStatus);
			if(task.getTitle()!=null)
				values.put("title", task.getTitle());
			if(task.getTag()!=null)
				values.put("tag",task.getTag());
			if(task.getFolder()!=null)
				values.put("folder",task.getFolder());
			if(task.getContext()!=null)
				values.put("context",task.getContext());
			if(task.getGoal()!=null)
				values.put("goal",task.getGoal());
			if(task.getLocation()!=null)
				values.put("location",task.getLocation());
			if(task.getParent()!=null)
				values.put("parent",task.getParent());
			if(task.getChildren()!=null)
				values.put("children",task.getChildren());
			if(task.getOrder()!=null)
				values.put("ord",task.getOrder());
			if(task.getDuedate()!=null)
				values.put("duedate",task.getDuedate());
			if(task.getDuedatemod()!=null)
				values.put("duedatemod",task.getDuedatemod());
			if(task.getStartdate()!=null)
				values.put("startdate",task.getStartdate());
			if(task.getDuetime()!=null)
				values.put("duetime",task.getDuetime());
			if(task.getStarttime()!=null)
				values.put("starttime",task.getStarttime());
			if(task.getRemind()!=null)
				values.put("remind",task.getRemind());
			if(task.getRepeat()!=null)
				values.put("repeat",task.getRepeat());
			if(task.getRepeatfrom()!=null)
				values.put("repeatfrom",task.getRepeatfrom());
			if(task.getStatus()!=null)
				values.put("status",task.getStatus());
			if(task.getLength()!=null)
				values.put("length",task.getLength());
			if(task.getPriority()!=null)
				values.put("priority",task.getPriority());
			if(task.getStar()!=null)
				values.put("star",task.getStar());
			if(task.getModified()!=null)
				values.put("modified",task.getModified());
			if(task.getCompleted()!=null)
				values.put("completed",task.getCompleted());
			if(task.getAdded()!=null)
				values.put("added",task.getAdded());
			if(task.getTimer()!=null)
				values.put("timer",task.getTimer());
			if(task.getTimeron()!=null)
				values.put("timeron",task.getTimeron());
			if(task.getNote()!=null)
				values.put("note",task.getNote());
			if(task.getMeta()!=null)
				values.put("meta",task.getMeta());
			rlt = db.getWritableDatabase().update("Task", values, where, null);
		}catch(Exception e){
			Log.e(Constant.TAG, "TaskDAO.update() error", e);
		}finally{
			if(db!=null) db.close();
		}
		
		return rlt>0;
	}
	
	public boolean updateStatus(long id, long status){
		long rlt = 0;
		try{
			db.openDataBase();			
			String where = "_id='"+id+"'";
			ContentValues values = new ContentValues();
			values.put("op_status", status);
			rlt = db.getWritableDatabase().update("Task", values, where, null);
		}catch(Exception e){
			Log.e(Constant.TAG, "TaskDAO.updateStatus error", e);
		}finally{
			if(db!=null) db.close();
		}
		
		return rlt>0;
	}
	
	public boolean updateFolder(long olderId, long newId){
		long rlt = 0;
		try{
			db.openDataBase();			
			String where = "folder="+olderId+"";
			ContentValues values = new ContentValues();
			//values.put("op_status", Constant.STATUS_SYNC_MODIFY);
			values.put("folder", newId);
			rlt = db.getWritableDatabase().update("Task", values, where, null);
		}catch(Exception e){
			Log.e(Constant.TAG, "TaskDAO.updateFolder error", e);
		}finally{
			if(db!=null) db.close();
		}
		
		return rlt>0;
	}
	
	public boolean updateContext(long olderId, long newId){
		long rlt = 0;
		try{
			db.openDataBase();			
			String where = "context="+olderId+"";
			ContentValues values = new ContentValues();
			values.put("context", newId);
			rlt = db.getWritableDatabase().update("Task", values, where, null);
		}catch(Exception e){
			Log.e(Constant.TAG, "TaskDAO.updateContext error", e);
		}finally{
			if(db!=null) db.close();
		}
		
		return rlt>0;
	}
	
	public boolean updateGoal(long olderId, long newId){
		long rlt = 0;
		try{
			db.openDataBase();			
			String where = "goal="+olderId+"";
			ContentValues values = new ContentValues();
			values.put("goal", newId);
			rlt = db.getWritableDatabase().update("Task", values, where, null);
		}catch(Exception e){
			Log.e(Constant.TAG, "TaskDAO.updateGoal error", e);
		}finally{
			if(db!=null) db.close();
		}
		
		return rlt>0;
	}
	
	public boolean delete(long id){
		long rlt = 0;
		try{
			String where = "_id="+id;
			db.openDataBase();
			rlt = db.getWritableDatabase().delete("Task", where,null);
		}catch(Exception e){
			Log.e(Constant.TAG, "TaskDAO.delete() error", e);
		}finally{
			if(db!=null) db.close();
		}
		
		return rlt>0;
	}
	
	public boolean delete(){
		long rlt = 0;
		try{
			db.openDataBase();
			rlt = db.getWritableDatabase().delete("Task", null,null);
		}catch(Exception e){
			Log.e(Constant.TAG, "FolderDAO.delete() error", e);
		}finally{
			if(db!=null) db.close();
		}
		
		return rlt>0;
	}
	
	public boolean delete(List<Task> tasks){
		long rlt = 0;
		try{
			String where = "_id=0";
			if(tasks.size()>0){
				String dw = "";
				for(Task task : tasks){
					dw += ","+task.getId()+"";
				}
				dw = dw.substring(1, dw.length());
				where = "_id in ("+dw+")";
			}
			db.openDataBase();
			rlt = db.getWritableDatabase().delete("Task", where,null);
		}catch(Exception e){
			Log.e(Constant.TAG, "TaskDAO.deleteWithoutIds() error", e);
		}finally{
			if(db!=null) db.close();
		}
		
		return rlt>0;
	}
	
	public Task get(long id){
		Task task = null;
		Cursor cursor = null;
		try{
			db.openDataBase();
			String where = "_id='"+id+"'";
			cursor = db.getReadableDatabase().query(true, "Task", Task.getColumns(), where,null, null, null, null, null);
			if(cursor!=null && cursor.moveToFirst()){
				task = parseCursor(cursor);
			}
		}catch(Exception e){
			Log.e(Constant.TAG, "FolderDAO.get(id) error", e);
		}finally{
			if(cursor!=null) cursor.close();
			if(db!=null) db.close();
		}
		
		return task;
	}
	
	public List<Task> getTaskByCompleted(String userid){
		List<Task> tasks = new ArrayList<Task>();
		Cursor cursor = null;
		try{
			db.openDataBase();			
			String where = "userid='"+userid+"' and completed>0";			
			String order = "completed desc";
			cursor = db.getReadableDatabase().query(true, "Task", Task.getColumns(), where,null, null, null, order, "25");
			if(cursor!=null && cursor.moveToFirst()){
				do{
					tasks.add(parseCursor(cursor));
				}while(cursor.moveToNext());
			}
		}catch(Exception e){
			Log.e(Constant.TAG, "TaskDAO.getTaskByCompleted() error", e);
		}finally{
			if(cursor!=null) cursor.close();
			if(db!=null) db.close();
		}
		return tasks;
	}
	
	public List<Task> getTaskBySyncStatus(long orderBy,String orderItem,String userid,long... statusLst){
		List<Task> tasks = new ArrayList<Task>();
		Cursor cursor = null;
		try{
			db.openDataBase();			
			String where = "userid='"+userid+"' ";
			if(statusLst!=null){
				where +=" and op_status in (-1";
				for(long status : statusLst){
					where += " ,"+status;
				}
				where +=" ) ";
			}
			
			String order = "added desc";
			if(orderItem!=null && orderItem.trim().length()>0){
				if(TaskListActivity.SORT_FOLDER.equals(orderItem)){
					order = "folder";
				}else if(TaskListActivity.SORT_START_DATE.equals(orderItem)){
					order = "startdate";
				}else if(TaskListActivity.SORT_DUE_DATE.equals(orderItem)){
					order = "duedate";
				}else if(TaskListActivity.SORT_PRIORITY.equals(orderItem)){
					order = "priority";
				}else if(TaskListActivity.SORT_STATUS.equals(orderItem)){
					order = "status";
				}else if(TaskListActivity.SORT_DATE_ADD.equals(orderItem)){
					order = "added";
				}else if(TaskListActivity.SORT_DATE_MODIFY.equals(orderItem)){
					order = "modified";
				}
				
				if(TaskListActivity.SORT_BY_RESERVES==orderBy){
					order += " desc";
				}
			}
			
			Log.d(Constant.TAG, "TaskDAO.get: where - "+where);
			cursor = db.getReadableDatabase().query(true, "Task", Task.getColumns(), where,null, null, null, order, null);
			if(cursor!=null && cursor.moveToFirst()){
				do{
					tasks.add(parseCursor(cursor));
				}while(cursor.moveToNext());
			}
		}catch(Exception e){
			Log.e(Constant.TAG, "TaskDAO.get(long... statusLst) error", e);
		}finally{
			if(cursor!=null) cursor.close();
			if(db!=null) db.close();
		}
		return tasks;
	}
		
	public boolean replaceId(long oid,long nid){
		long rlt = 0;
		try{
			db.openDataBase();
			String where = "_id="+oid;
			ContentValues values = new ContentValues();
			values.put("_id", nid);
			rlt = db.getWritableDatabase().update("Task", values, where, null);
		}catch(Exception e){
			Log.e(Constant.TAG, "TaskDAO.replaceId() error", e);
		}finally{
			if(db!=null) db.close();
		}
		
		return rlt>0;
	}
	
	private Task parseCursor(Cursor cursor){
		Task task = new Task();
		task.setId(cursor.getLong(0)); 
		task.setUserid(cursor.getString(1));
		task.setTitle(cursor.getString(2));
		task.setTag(cursor.getString(3));
		task.setFolder(cursor.getLong(4));
		task.setContext(cursor.getLong(5));
		task.setGoal(cursor.getLong(6));
		task.setParent(cursor.getLong(7));
		task.setChildren(cursor.getLong(8));
		task.setOrder(cursor.getLong(9));
		task.setDuedate(cursor.getLong(10));
		task.setDuedatemod(cursor.getLong(11));
		task.setStartdate(cursor.getLong(12));
		task.setDuetime(cursor.getLong(13));
		task.setStarttime(cursor.getLong(14));
		task.setRemind(cursor.getLong(15));
		task.setRepeat(cursor.getString(16));
		task.setRepeatfrom(cursor.getLong(17));
		task.setStatus(cursor.getLong(18));
		task.setLength(cursor.getLong(19));
		task.setPriority(cursor.getLong(20));
		task.setStar(cursor.getLong(21));
		task.setModified(cursor.getLong(22));
		task.setCompleted(cursor.getLong(23));
		task.setAdded(cursor.getLong(24));
		task.setTimer(cursor.getLong(25));
		task.setTimeron(cursor.getLong(26));
		task.setMeta(cursor.getString(27));
		task.setNote(cursor.getString(28));
		return task;
	}
	
}
